﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Text;
using WAD.WEB.AppCode;
using WAD.DAL;
using WAD.Model;
using GL.Tools;
using WAD.WEB.AppCode.Sms;
using System.Web.SessionState;

namespace WAD.WEB.Client2.Ajax
{
    /// <summary>
    /// User 的摘要说明
    /// </summary>
    public partial class User : AjaxBase
    {
        public override void AjaxMethodDispatch(String identity)
        {
            switch (identity)
            {
                case "regist": this.Regist(); break;
                case "login": this.Login(); break;
                case "getdetail": this.GetDetail(); break;
                case "getagentid": this.GetAgentId(); break;
                case "getarticlelogo": this.GetArticleLogo(); break;
                case "updateinfo": this.UpdateInfo(); break;
                case "validatephone": this.ValidatePhone(); break;
                case "modifypwd": this.ModifyPwd(); break;
                case "forgetpwd": this.ForgetPwd(); break;
                case "resetpwdbyphone": this.ResetPwdByPhone(); break;
                case "vipapply": this.VipApply(); break;
                case "send_r": this.Send_R(); break;
                case "getbalance": this.GetBalance(); break;
                case "sendsmscode": this.SendSMSCode(); break;
                case "changelogin": this.ChangeLogin(); break;
            }
        }
        /// <summary>
        /// 注册
        /// </summary>
        [QD.Web.Ajax.AjaxMethod]
        public void Regist()
        {
            int loginType = Parse.Int("login_type", 0);//登陆方式
            if (loginType == 0)
            {
                ParamError();
            }

            MUser m = new MUser();
            m.login_type = loginType;
            m.agentid = 0;
            if (loginType == 1)
            {
                //站内注册
                String name = Parse.String("name");//用户名
                String pwd = Parse.String("pwd");//密码
                String phone = Parse.String("phone");//电话
                String email = Parse.String("email");//邮件
                String qq = Parse.String("qq");//qq

                if (String.IsNullOrEmpty(name) || String.IsNullOrEmpty(pwd) || String.IsNullOrEmpty(phone) || String.IsNullOrEmpty(email))
                {
                    ParamError();
                }

                m.name = name;
                m.nick_name = name;
                m.phone = phone;
                m.pwd = StringHelper.MD5Encrypt(pwd);
                m.qq = qq;
                m.email = email;

                m.agentid = Parse.Int("agentid", 0); //代理商ID
                if (Parse.String("nick_name", "") != "")
                {
                    m.nick_name = Parse.String("nick_name", "");
                }
            }
            else if (loginType == 4)
            {
                //手机号注册
                String phone = Parse.String("phone");//手机号
                String smsCode = Parse.String("code");//验证码
                String pwd = Parse.String("pwd");//密码
                int adminId = Parse.Int("agentid", 0);//推介人id

                if (String.IsNullOrEmpty(phone) || String.IsNullOrEmpty(smsCode) || String.IsNullOrEmpty(pwd))
                {
                    ParamError();
                }

                if (!SMSHelper.ValidateCode(phone, smsCode))
                {
                    //验证码不正确
                    JsonResult(Message.Code.ERROR_SMS_CODE, Message.Msg.ERROR_SMS_CODE);
                }

                m.name = "Tel:" + StringHelper.RandomNumber(10);
                m.nick_name = phone;
                m.phone = phone;
                m.pwd = StringHelper.MD5Encrypt(pwd);
                m.agentid = adminId;
            }
            else
            {

                //第三方注册接口
                String apiRs = Parse.String("api_rs");//第三方登陆返回值
                if (String.IsNullOrEmpty(apiRs))
                {
                    ParamError();
                }
                String nickName = Parse.String("nick_name");//昵称
                String logo = Parse.String("logo");//昵称

                m.api_rs = apiRs;
                m.nick_name = nickName;
                m.logo = logo;
            }

            int code = DaoUser.Regist(m);

            switch (code)
            {
                case Message.Code.USER_EXIST:
                    JsonResult(Message.Code.USER_EXIST, Message.Msg.USER_EXIST);
                    break;
                case Message.Code.EMAIL_EXIST:
                    JsonResult(Message.Code.EMAIL_EXIST, Message.Msg.EMAIL_EXIST);
                    break;
                case Message.Code.PHONE_EXIST:
                    JsonResult(Message.Code.PHONE_EXIST, Message.Msg.PHONE_EXIST);
                    break;
                case Message.Code.SUCCESS:
                    Login();
                    break;
                default:
                    ;
                    break;
            }
        }

        /// <summary>
        /// 登陆接口
        /// </summary>
        [QD.Web.Ajax.AjaxMethod]
        public void Login()
        {
            int loginType = Parse.Int("login_type", 0);//登陆方式
            if (loginType == 0)
            {
                ParamError();
            }

            MUser m = new MUser();
            m.login_type = loginType;

            if (loginType == 1)
            {
                //站内注册
                String name = Parse.String("name");//用户名
                String pwd = Parse.String("pwd");//密码

                if (String.IsNullOrEmpty(name) || String.IsNullOrEmpty(pwd))
                {
                    ParamError();
                }

                m.name = name;
                m.pwd = StringHelper.MD5Encrypt(pwd);
            }
            else if (loginType == 4)
            {

                //站内注册
                String phone = Parse.String("phone");//手机号
                String pwd = Parse.String("pwd");//密码

                if (String.IsNullOrEmpty(phone) || String.IsNullOrEmpty(pwd))
                {
                    ParamError();
                }

                m.phone = phone;
                m.pwd = StringHelper.MD5Encrypt(pwd);
            }
            else
            {

                //第三方注册接口
                String apiRs = Parse.String("api_rs");//第三方登陆返回值
                if (String.IsNullOrEmpty(apiRs))
                {
                    ParamError();
                }
                m.api_rs = apiRs;
            }

            //登陆数据
            Dictionary<String, object> data = null;
            int code = DaoUser.Login(m, out data);

            switch (code)
            {
                case Message.Code.ERROR_NAME:

                    if (loginType == 3)
                    //微信登录时处理
                    {
                        m.api_rs = Parse.String("openid");
                        code = DaoUser.Login(m, out data);

                        switch (code)
                        {
                            case Message.Code.ERROR_NAME:
                                JsonResult(Message.Code.ERROR_NAME, Message.Msg.ERROR_NAME);
                                break;
                            case Message.Code.SUCCESS:
                                SavaLog("2", "APP更新UnionID " + string.Format("update [user] set api_rs='{0}' where api_rs='{1}' and id={2}", Parse.String("api_rs"), m.api_rs, data["id"]));
                                //更新api_rs
                                DAO.ExecuteNonQuery(string.Format("update [user] set api_rs='{0}' where api_rs='{1}' and id={2}", Parse.String("api_rs"), m.api_rs, data["id"]));

                                Success(data);
                                break;
                        }
                    }

                    JsonResult(Message.Code.ERROR_NAME, Message.Msg.ERROR_NAME);
                    break;
                case Message.Code.ERROR_PWD:
                    JsonResult(Message.Code.ERROR_PWD, Message.Msg.ERROR_PWD);
                    break;
                case Message.Code.ERROR_STATE:
                    JsonResult(Message.Code.ERROR_STATE, Message.Msg.ERROR_STATE);
                    break;
                case Message.Code.NO_PHONE:
                    JsonResult(Message.Code.NO_PHONE, Message.Msg.NO_PHONE);
                    break;
                case Message.Code.SUCCESS:

                    Success(data);
                    break;
                default:
                    ;
                    break;
            }
        }


        /// <summary>
        /// 用户详细信息
        /// </summary>
        [QD.Web.Ajax.AjaxMethod]
        public void GetDetail()
        {
            IsLogin();
            Dictionary<string, object> dic = DaoUser.GetDetail(UserId, "id,name,nick_name,pwd as isupdate,email,phone,is_validate_phone,wx_code,wx_public_code,tel,qq,logo,parent_id");
            if (dic != null && dic["isupdate"] != DBNull.Value)
                dic["isupdate"] = 1;
            else
                dic["isupdate"] = 0;
            Dictionary<string, object> version = DaoUserVersion.GetByUserId(UserId);
            if (version != null)
            {
                dic.Add("version", DaoUserVersion.GetVersion(UserId));
                dic.Add("end_date", version["end_date"]);
            }
            version = null;
            Success(dic);
        }
        /// <summary>
        /// 获取推荐人ID
        /// </summary>
        [QD.Web.Ajax.AjaxMethod]
        public void GetAgentId()
        {
            IsLogin();
            Dictionary<string, object> dic = DaoUser.GetDetail(UserId, "agentid");
            Success(dic);
        }

        /// <summary>
        /// 获取文章封面图片
        /// </summary>
        [QD.Web.Ajax.AjaxMethod]
        public void GetArticleLogo()
        {
            IsLogin();
            Dictionary<string, object> dic = DaoUser.GetDetail(UserId, "articlelogo");
            Success(dic);
        }

        /// <summary>
        /// 修改资料
        /// </summary>
        [QD.Web.Ajax.AjaxMethod]
        public void UpdateInfo()
        {
            IsLogin();

            //邮箱
            String email = Parse.String("email");

            //logo
            String logo = Parse.String("logo");

            //手机
            String phone = Parse.String("phone");

            //推广电话
            String tel = Parse.String("tel");

            //qq
            String qq = Parse.String("qq");

            //昵称
            String nickName = Parse.String("nick_name");
            String article_logo = Parse.String("articlelogo", "");

            //上级id
            int parentId = Parse.Int("parent_id", 0);

            //推介人id
            int agent_id = Parse.Int("agentid", 0);

            //微信二维码结果
            String wxCode = Parse.String("wx_code");

            //订阅号二维码结果
            String wx_public_code = Parse.String("wx_public_code");

            if (String.IsNullOrEmpty(email) && String.IsNullOrEmpty(logo)
                && String.IsNullOrEmpty(phone) && String.IsNullOrEmpty(tel) && String.IsNullOrEmpty(qq)
                && String.IsNullOrEmpty(nickName) && parentId < 0
                && String.IsNullOrEmpty(wxCode) && String.IsNullOrEmpty(wx_public_code))
            {
                ParamError();
            }

            //修改手机号时验证手机号
            if (!String.IsNullOrEmpty(phone))
            {
                //得到短信验证码
                String smsCode = Parse.String("code");
                if (!SMSHelper.ValidateCode(phone, smsCode))
                {
                    //验证码不正确
                    JsonResult(Message.Code.ERROR_SMS_CODE, Message.Msg.ERROR_SMS_CODE);
                }
            }

            MUser m = new MUser() { id = UserId, logo = logo, email = email, qq = qq, nick_name = nickName, phone = phone, tel = tel, parent_id = parentId, agentid = agent_id, articlelogo = article_logo, wx_code = wxCode, wx_public_code = wx_public_code };

            int code = DaoUser.UpdateInfo(m);

            if (code == 1013)
                JsonResult(1013, "推荐人ID有误");
            else if (code == 1004)
                JsonResult(1014, "不允许修改推荐人ID");

            switch (code)
            {
                case Message.Code.EMAIL_EXIST:
                    JsonResult(Message.Code.EMAIL_EXIST, Message.Msg.EMAIL_EXIST);
                    break;
                case Message.Code.PHONE_EXIST:
                    JsonResult(Message.Code.PHONE_EXIST, Message.Msg.PHONE_EXIST);
                    break;
                case Message.Code.SUCCESS:
                    Success();
                    break;
                default:
                    Fail();
                    break;
            }
        }

        /// <summary>
        /// 验证手机号
        /// </summary>
        [QD.Web.Ajax.AjaxMethod]
        public void ValidatePhone()
        {
            IsLogin();
            String phone = Parse.String("phone");
            String smsCode = Parse.String("code");

            if (String.IsNullOrEmpty(phone))
            {
                ParamError();
            }

            //验证手机号
            if (!SMSHelper.ValidateCode(phone, smsCode))
            {
                //验证码不正确
                JsonResult(Message.Code.ERROR_SMS_CODE, Message.Msg.ERROR_SMS_CODE);
            }

            if (DaoUser.ValidatePhone(UserId, phone))
            {
                Success();
            }
            else
            {
                Fail();
            }
        }

        /// <summary>
        /// 修改密码
        /// </summary>
        [QD.Web.Ajax.AjaxMethod]
        public void ModifyPwd()
        {
            IsLogin();
            String newPwd = Parse.String("new_pwd");
            String oldPwd = Parse.String("old_pwd");

            if (String.IsNullOrEmpty(newPwd) || String.IsNullOrEmpty(oldPwd))
            {
                ParamError();
            }

            if (DaoUser.ModifyPwd(UserId, StringHelper.MD5Encrypt(oldPwd), StringHelper.MD5Encrypt(newPwd)))
            {
                Success();
            }
            else
            {
                Fail();
            }
        }


        /// <summary>
        /// 忘记密码
        /// </summary>
        [QD.Web.Ajax.AjaxMethod]
        public void ForgetPwd()
        {
            string email = Parse.String("email");
            string name = Parse.String("name");
            if (String.IsNullOrEmpty(email) || String.IsNullOrEmpty(name))
            {
                ParamError();
            }

            MUser m = DaoUser.GetEntityByName(name);
            if (m == null)
            {
                //用户名不存在
                JsonResult(Message.Code.ERROR_NAME, Message.Msg.ERROR_NAME);
            }

            if (m.login_type != 1)
            {
                //使用的第三方登录  无需找回密码  请直接使用第三方登录

                switch (m.login_type)
                {
                    case 2: JsonResult(Message.Code.FORGET_LOGIN_QQ, Message.Msg.FORGET_LOGIN_QQ); break;
                    case 3: JsonResult(Message.Code.FORGET_LOGIN_WX, Message.Msg.FORGET_LOGIN_WX); break;
                }
            }

            if (!email.Equals(m.email))
            {
                JsonResult(Message.Code.ERROR_EMAIL, Message.Msg.ERROR_EMAIL);
            }

            String newPwd = StringHelper.Random(6);
            if (DaoUser.ModifyPwd(m.id, m.pwd, QD.Utils.Encrypt.MD5(newPwd)))
            {
                EmailHelper.Send(m.email, "密码重置", "密码已经重置，您的新密码为：" + newPwd + "，请妥善保管！");
                JsonResult(Message.Code.FORGET_SUCCESS, Message.Msg.FORGET_SUCCESS);
            }
            else
            {
                Fail();
            }

        }

        /// <summary>
        /// 忘记密码-通手机号找回
        /// </summary>
        [QD.Web.Ajax.AjaxMethod]
        public void ResetPwdByPhone()
        {
            string phone = Parse.String("phone");
            String smsCode = Parse.String("code");
            String pwd = Parse.String("pwd");
            if (String.IsNullOrEmpty(phone) || String.IsNullOrEmpty(smsCode) || String.IsNullOrEmpty(pwd))
            {
                ParamError();
            }

            MUser m = DaoUser.GetEntityByPhone(phone);
            if (m == null)
            {
                //改手机不存在
                JsonResult(Message.Code.NO_PHONE, Message.Msg.NO_PHONE);
            }

            if (!m.is_validate_phone)
            {
                //该手机未验证
                JsonResult(Message.Code.NO_VALIDATE_PHONE, Message.Msg.NO_VALIDATE_PHONE);
            }


            if (!SMSHelper.ValidateCode(phone, smsCode))
            {
                //验证码不正确
                JsonResult(Message.Code.ERROR_SMS_CODE, Message.Msg.ERROR_SMS_CODE);
            }

            String newPwd = pwd;
            if (DaoUser.ModifyPwd(m.id, m.pwd, QD.Utils.Encrypt.MD5(newPwd)))
            {
                Success();
            }
            else
            {
                Fail();
            }

        }

        /// <summary>
        /// 用户vip申请
        /// </summary>
        [QD.Web.Ajax.AjaxMethod]
        public void VipApply()
        {
            int user_id = Parse.Int("user_id", 0);
            String company = Parse.String("company");//公司
            String phone = Parse.String("phone");//电话
            String contact = Parse.String("contact");//联系人
            String email = Parse.String("email");//contact
            String summary = Parse.String("summary");//备注
            bool isFirst = true;
            //验证
            if (String.IsNullOrEmpty(company) || String.IsNullOrEmpty(phone) || String.IsNullOrEmpty(contact) || String.IsNullOrEmpty(email))
            {
                ParamError();
            }

            StringBuilder sb = new StringBuilder();
            sb.Append("公司:").Append(company).Append("<br />").Append("电话:").Append(phone).Append("<br />").Append("联系人:").Append(contact).Append("<br />").Append("邮箱:").Append(email).Append("<br />").Append("备注:").Append(summary);

            string agentid="";
            if (user_id > 0)
            {
                Dictionary<string, object> agent = DaoUser.GetParentAgent(user_id, "email,agentid");
                //发邮件给代理商
                if (agent != null && agent["email"] != DBNull.Value)
                {
                    string agentEmail = Convert.ToString(agent["email"]);
                    agentid=Convert.ToString("agentid");
                    if (!string.IsNullOrEmpty(email))
                        EmailHelper.Send(agentEmail, "微街秀申请正式版", sb.ToString());
                    isFirst = false;
                }
            }

            if (isFirst)
                EmailHelper.Send(WJXConfig.EmailConfig.KF_Email, "微街秀申请正式版", sb.ToString());
            else
            {
                sb.Append("<br/>微街秀代理商ID：" + agentid);
                EmailHelper.Send(WJXConfig.EmailConfig.KF_Email, "微街秀申请正式版[抄送邮件]", sb.ToString());
            }
            Success();
        }


        /// <summary>
        ///  开通申请
        /// </summary>
        [QD.Web.Ajax.AjaxMethod]
        public void Send_R()
        {
            int user_id = Parse.Int("user_id", 0);
            String company = Parse.String("CompanyName");//公司
            String phone = Parse.String("Phone");//电话
            String contact = Parse.String("Linkman");//联系人
            String email = Parse.String("Email");//contact
            String Content = Parse.String("Content");//备注
            string Intent = Parse.String("Intent");//合作意向
            string refs = Parse.String("ref");//来源地址
            bool isFirst = true;
            //验证
            if (String.IsNullOrEmpty(Intent) || String.IsNullOrEmpty(company) || String.IsNullOrEmpty(phone) || String.IsNullOrEmpty(contact) || String.IsNullOrEmpty(email))
            {
                ParamError();
            }
            StringBuilder sb = new StringBuilder();
            sb.AppendFormat("公司名称：{0}<br />", company)
                .AppendFormat("联系人：{0}<br />", contact)
                .AppendFormat("联系电话：{0}<br />", phone)
                .AppendFormat("电子信箱：{0}<br />", email)
                .AppendFormat("合作意向：{0}<br />", Intent)
                .AppendFormat("留言：{0}<br />", Content)
                .AppendFormat("登记时间：{0}<br />", DateTime.Now.ToString())
                .AppendFormat("来源网址：{0}", refs);

            string agentid = "";
            if (user_id > 0)
            {
                Dictionary<string, object> agent = DaoUser.GetParentAgent(user_id, "email,agentid");
                //发邮件给代理商
                if (agent != null && agent["email"] != DBNull.Value)
                {
                    string agentEmail = Convert.ToString(agent["email"]);
                    agentid = Convert.ToString(agent["agentid"]);
                    if (!string.IsNullOrEmpty(email))
                        EmailHelper.Send(agentEmail, "微街秀申请正式版", sb.ToString());
                    isFirst = false;
                }
            }

            if (isFirst)
                EmailHelper.Send(WJXConfig.EmailConfig.KF_Email, "微街秀申请正式版", sb.ToString());
            else
            {
                sb.Append("<br/>微街秀代理商ID：" + agentid);
                EmailHelper.Send(WJXConfig.EmailConfig.KF_Email, "微街秀申请正式版[抄送邮件]", sb.ToString());
            }
            Success();
        }

        /// <summary>
        /// 获取余额
        /// </summary>
        [QD.Web.Ajax.AjaxMethod]
        public void GetBalance()
        {
            int type = Parse.Int("type", 0); // 1 广告主, 2 分享主
            if (type != 1 && type != 2)
                ParamError();
            IsLogin();
            Dictionary<string, object> model = DaoUser.Get("user", "id=" + userBean.id, "ad_balance,shared_balance");
            if (type == 1)
                JsonResult(0, "", GetBalance(model["ad_balance"]));
            else if (type == 2)
                JsonResult(0, "", GetBalance(model["shared_balance"]));
            JsonResult(0, "", 0);
        }

        /// <summary>
        /// 发送验证码
        /// </summary>
        [QD.Web.Ajax.AjaxMethod]
        public void SendSMSCode()
        {
            //验证码类型
            String type = Parse.String("type");

            //接收验证码的手机号
            String phone = Parse.String("phone");
            if (String.IsNullOrEmpty(phone) || String.IsNullOrEmpty(type))
            {
                ParamError();
            }

            type = type.ToLower();

            bool isSuccess = false;
            if (type.Equals("regist"))
            {
                if (DaoUser.IsSamePhone(phone))
                {
                    //该手机号已注册
                    JsonResult(Message.Code.PHONE_EXIST, Message.Msg.PHONE_EXIST);
                }
                isSuccess = SMSHelper.Regist(phone);
            }
            else if (type.Equals("login"))
            {
                isSuccess = SMSHelper.Login(phone);
            }
            else if (type.Equals("reset"))
            {
                if (DaoUser.IsSamePhone(phone))
                {
                    //该手机号已注册
                    JsonResult(Message.Code.PHONE_EXIST, Message.Msg.PHONE_EXIST);
                }
                isSuccess = SMSHelper.Modify(phone);
            }
            else if (type.Equals("modify"))
            {
                if (!DaoUser.IsSamePhone(phone))
                {
                    //该手机号未注册
                    JsonResult(Message.Code.NO_PHONE, Message.Msg.NO_PHONE);
                }
                isSuccess = SMSHelper.Modify(phone);
            }
            else
            {
                Fail();
            }

            if (isSuccess)
            {
                Success();
            }
            else
            {
                Fail();
            }

        }


        /// <summary>
        /// 微信转手机用户
        /// </summary>
        [QD.Web.Ajax.AjaxMethod]
        public void ChangeLogin()
        {
            IsLogin();
            string phone = Parse.String("phone");
            String smsCode = Parse.String("code");
            String pwd = Parse.String("pwd");
            if (String.IsNullOrEmpty(phone) || String.IsNullOrEmpty(smsCode) || String.IsNullOrEmpty(pwd))
            {
                ParamError();
            }

            MUser m = DaoUser.GetEntityByPhone(phone);

            if (m != null && m.id.Value != UserId)
            {
                JsonResult(11, "手机号被其他账号使用");
            }

            if (!SMSHelper.ValidateCode(phone, smsCode))
            {
                //验证码不正确
                JsonResult(Message.Code.ERROR_SMS_CODE, Message.Msg.ERROR_SMS_CODE);
            }

            int count = DaoUser.ExecuteNonQuery(string.Format("update [user] set phone='{0}',pwd='{1}',is_validate_phone=1 where id={2}", phone, QD.Utils.Encrypt.MD5(pwd), UserId));
            if (count > 0)
                Success();
            else
                Fail();
        }


        static decimal GetBalance(object money)
        {
            //return Convert.ToDecimal(money);
            string s = Convert.ToString(money);
            if (string.IsNullOrEmpty(s))
                return 0;

            s = QD.Utils.Encrypt.Decode(s, WJXConfig.EncryptConfig.DES_KEY); //DES解密
            if (string.IsNullOrEmpty(s))
                return 0;
            return Convert.ToDecimal(s);
        }
    }
}